package com.huike.pmps.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.pmps.dao.PaymentCollectionDao;
import com.huike.pmps.model.constants.GlobalConstants;
import com.huike.pmps.model.dto.common.PageInfo;
import com.huike.pmps.model.entity.PaymentCollection;
import com.huike.pmps.model.entity.Provinces;
import com.huike.pmps.model.entity.Region;
import com.huike.pmps.model.vo.PageResult;
import com.huike.pmps.model.vo.Result;
import com.huike.pmps.service.PaymentCollectionService;
import com.huike.pmps.service.ProvincesService;
import com.huike.pmps.service.RegionService;
import com.huike.pmps.utils.PmpUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 作者：谌贵斌(黑桃K)
 * 日期: 2888-08-08
 * 老师QQ: 272488352
 * 官方QQ交流群: 377748272
 * 刀客程序员官网：http://www.daoke360.com
 * 刀客程序员淘宝旗舰店：https://daoke360.taobao.com/
 */
@Service
public class PaymentCollectionServiceImpl implements PaymentCollectionService {
    @Autowired
    RegionService regionService;
    @Autowired
    ProvincesService provincesService;
    @Autowired
    PaymentCollectionDao paymentCollectionDao;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public Result insertByImportPaymentCollection(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.failure("文件为空");
        }
        int count = 0;
        try {
            //根据路径获取这个操作excel的实例
            XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
            //根据页面index 获取sheet页
            XSSFSheet sheet = wb.getSheetAt(0);
            //获取标题行
            XSSFRow titleRow = sheet.getRow(0);
            String[] titleRowArray = new String[]{"回款日期", "回款金额", "省区", "战区", "财年","产品类型"};
            for (int i = 0; i < titleRowArray.length; i++) {
                if (!titleRowArray[i].equals(titleRow.getCell(i).getStringCellValue()))
                    return Result.failure("模板标题行已被修改，请勿修改供应商模板标题行");
            }
            List<PaymentCollection> paymentCollectionList = new ArrayList<>();
            XSSFRow row = null;
            Date date = new Date();
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                //获取每一行数据
                count++;
                row = sheet.getRow(i);

                //回款金额
                if (row.getCell(0) == null|| StringUtils.isBlank(row.getCell(0).toString())) return Result.failure("本次导入全部失败，第【" + i + "】条数据 回款日期 为空");
                Date paymentDate = row.getCell(0).getDateCellValue();
                Integer year = PmpUtil.getDateInfo(paymentDate, GlobalConstants.YEAR);
                Integer weekOfYear = PmpUtil.getDateInfo(paymentDate, GlobalConstants.WEEK_OF_YEAR);
                Integer seasonOfYear = PmpUtil.getDateInfo(paymentDate, GlobalConstants.SEASON);
                Integer monthOfYear = PmpUtil.getDateInfo(paymentDate, GlobalConstants.MONTH);

                //回款金额
                if (row.getCell(1) == null|| StringUtils.isBlank(row.getCell(1).toString())) return Result.failure("本次导入全部失败，第【" + i + "】条数据 回款金额 为空");
                BigDecimal collectionAmount = BigDecimal.valueOf(Double.valueOf(row.getCell(1).toString()));

              /*  //季度
                if (row.getCell(2) == null|| StringUtils.isBlank(row.getCell(2).toString())) return Result.failure("本次导入全部失败，第【" + i + "】条数据 季度 为空");
                String season = row.getCell(2).toString();*/


                //省区和战区
                Integer regionId, provinceId = null;
                String regionName, provinceName = null;
                if (row.getCell(2) == null|| StringUtils.isBlank(row.getCell(2).toString())) {
                    return Result.success("本次导入全部失败，第" + i + "条数据,省份为空，本次导入全部失败");
                } else {
                    Provinces provinces = provincesService.selectByProvinceName(row.getCell(2).toString().substring(0, 2));
                    if (provinces != null) {
                        provinceId = provinces.getProvinceId();
                        provinceName = provinces.getProvince();
                    } else {
                        return Result.success("本次导入全部失败，第" + i + "条数据,省份数据填写有误,请按规则填写");
                    }
                }
                if (row.getCell(3) == null|| StringUtils.isBlank(row.getCell(3).toString())) {
                    return Result.success("本次导入全部失败，第" + i + "条数据,战区为空，本次导入全部失败");
                } else {
                    Region region = regionService.selectOneByRegionName(row.getCell(3).toString().substring(0, 2));
                    if (region != null) {
                        regionId = region.getId();
                        regionName = region.getRegion();
                    } else {
                        return Result.success("本次导入全部失败，第" + i + "条数据,战区数据填写有误,请按规则填写");
                    }
                }
                //所属财年
                Integer financialYear = null;
                if (row.getCell(4) == null|| StringUtils.isBlank(row.getCell(4).toString())) {
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 所属财年 为空");
                } else {
                    if (row.getCell(4).toString().startsWith("FY") && row.getCell(4).toString().endsWith("19")) {
                        financialYear = 2019;
                    } else if (row.getCell(4).toString().startsWith("FY") && row.getCell(4).toString().endsWith("20")) {
                        financialYear = 2020;
                    } else if (row.getCell(4).toString().startsWith("FY") && row.getCell(4).toString().endsWith("21")) {
                        financialYear = 2021;
                    } else if (row.getCell(4).toString().startsWith("FY") && row.getCell(4).toString().endsWith("22")) {
                        financialYear = 2022;
                    } else {
                        financialYear = 2020;
                    }
                }

                //产品品类
                Integer productTypeId = null;
                String productTypeName = null;
                if (row.getCell(5) == null|| StringUtils.isBlank(row.getCell(5).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 产品品类 为空");
                else {
                    productTypeName = row.getCell(5).toString();
                    if (productTypeName.contains("高校邦平台")||productTypeName.contains("基于高校邦的课程运营服务")||productTypeName.contains("高校邦运营服务")) {
                        productTypeId = 1;
                        productTypeName = redisTemplate.opsForHash().get(GlobalConstants.REDIS_HASH_DICTIONARY_DATA, 1).toString();
                    }
                    if (productTypeName.contains("精品在线")) {
                        productTypeId = 2;
                        productTypeName = redisTemplate.opsForHash().get(GlobalConstants.REDIS_HASH_DICTIONARY_DATA, 2).toString();
                    }
                    if (productTypeName.contains("拍摄与制作")) {
                        productTypeId = 3;
                        productTypeName = redisTemplate.opsForHash().get(GlobalConstants.REDIS_HASH_DICTIONARY_DATA, 3).toString();
                    }
                    if (productTypeName.contains("高校邦学习平台")) {
                        productTypeId = 4;
                        productTypeName = redisTemplate.opsForHash().get(GlobalConstants.REDIS_HASH_DICTIONARY_DATA, 4).toString();
                    }
                }

                PaymentCollection paymentCollection = PaymentCollection.builder().year(year).regionId(regionId).regionName(regionName).provinceId(provinceId)
                        .provinceName(provinceName).financialYear(financialYear).collectionAmount(collectionAmount).paymentDate(paymentDate).productTypeId(productTypeId)
                        .productTypeName(productTypeName).weekOfYear(weekOfYear).seasonOfYear(seasonOfYear).monthOfYear(monthOfYear).createTime(date).build();
                paymentCollectionList.add(paymentCollection);
            }
            if (paymentCollectionList.size() > 0) {
                paymentCollectionDao.insertBatchList(paymentCollectionList);
                return Result.success("全部导入成功");
            } else {
                return Result.failure("表格中没有数据");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Result.failure("本次导入全部失败，读取表格数据异常" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.success("本次导入全部失败，第" + count + "条数据解析异常");
        }
    }

    @Override
    public Result selectByCondition(PageInfo pageInfo, Integer regionId, Integer provinceId) {
        QueryWrapper<PaymentCollection> queryWrapper = new QueryWrapper<>();
        if (regionId != null)
            queryWrapper.eq("region_id", regionId);

        if (provinceId != null)
            queryWrapper.eq("province_id", provinceId);
        Page<PaymentCollection> page = new Page<>(pageInfo.getPage(), pageInfo.getPageSize());
        Page<PaymentCollection> pageList = paymentCollectionDao.selectPage(page, queryWrapper);
        if (pageList.getSize() > 0) {
            PageResult pageResult = PageResult.builder().pageNumber(pageList.getCurrent()).pageSize(pageList.getSize())
                    .total(pageList.getTotal()).rows(pageList.getRecords()).build();
            return Result.success(pageResult);
        } else {
            return Result.success("没有符合条件的记录");
        }


    }




}
